<template>
  <div class="search">
    <div>
      <!-- 搜索页面 -->
      <form action="/">
        <van-search v-if="isSearchBox" v-model="inputValue" show-action
          :placeholder="searchInit?.defaultKeyword?.keyword" @search="onSearch" @update:model-value="onchange"
          @cancel="onCancel" @clear="(isShowSearch = false), (isPageDetail = false)" />
        <van-search v-else v-model="inputValue" :placeholder="searchInit?.defaultKeyword?.keyword" />
      </form>

      <div v-show="!isShowSearch && !isPageDetail">
        <!-- 历史记录页面 -->
        <div class="record">
          <div class="header">
            <span>历史记录</span>
            <van-icon class="icon" name="delete-o" @click="deleted" />
          </div>
          <div class="detail">
            <van-tag plain text-color="black" color="#999" type="primary" size="large"
              v-for="historyData in historyList" :key="historyData" @click="btnSearch(historyData)">{{
                historyData
              }}</van-tag>
          </div>
        </div>
        <!-- 热门搜索页面 -->
        <div class="hot">
          <div class="goods">
            <span>热门搜索</span>
          </div>
          <div class="detail">
            <van-tag :class="searchHot.highlight === 1 ? 'active' : ''" v-for="searchHot in searchInit.hotKeywordVOList"
              :key="searchHot.keyword" plain type="primary" size="large" @click="btnSearch(searchHot.keyword)">{{
                searchHot.keyword
              }}</van-tag>
          </div>
        </div>
      </div>

      <!-- 搜索框触发的实时请求列表页面 -->
      <div v-show="isShowSearch && !isPageDetail">
        <van-cell is-link v-for="realData in realTimeList" :key="realData" :title="realData"
          @click="btnSearch(realData)" />
      </div>
    </div>

    <div>
      <!-- 搜索的商品详情页面 -->
      <div class="detail-goods" v-show="isPageDetail && !notfound">
        <div class="top">
          <div>综合</div>
          <div>价格</div>
          <div>分类</div>
        </div>
        <div class="similar-goods">
          <div class="similar" v-for="items in searchDetail" :key="items.id">
            <img class="bigimg" :src="items.listPicUrl" alt="图片加载出错" />
            <img class="smallimg" :src="items.preLogo[0]?.logoUrl" alt="" />
            <span>{{ items.name }}</span>
            <div class="price">
              <span style="font-size: 20px; color: red">￥{{ items.retailPrice }}</span>
              <span v-if="!items.counterPrice"></span>
              <span v-else class="original-price">￥{{ items.counterPrice }}</span>
            </div>
            <div class="content-special" v-if="items.finalPriceInfoVO.banner?.title">
              <span>{{ items.finalPriceInfoVO.banner?.title }}</span>
              <span>{{ items.finalPriceInfoVO.banner?.content }}</span>
            </div>
            <div class="content-full" v-else-if="items.finalPriceInfoVO.banner?.content">
              {{ items.finalPriceInfoVO.banner?.content }}
            </div>
          </div>
        </div>
      </div>
      <!-- 搜索无的页面 -->
      <div v-show="notfound && isPageDetail" class="nofound">
        <img src="https://hbimg.b0.upaiyun.com/1e115bea1361825ea6dae3f20aea16027fa8aa348ca7-PYLM3j_fw658" alt="" />
        <span style="font-size: 20px">你搜索的商品未上架</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import {
  reqGetInitData,
  reqGetRealTime,
  reqSearchDetail,
} from "@/api/search/search";
import { useRouter } from "vue-router";

// 输入框的展示情况
const inputValue = ref();
//默认关键字和热门搜索
const searchInit = ref({});
// 实时展示搜索情况状态
const isShowSearch = ref();
// 搜索页面和详情页面状态切换
const isPageDetail = ref();
// 搜索框状态
const isSearchBox = ref(true);
// 实时列表数据
const realTimeList = ref({});
// 历史数据列表
const historyList = ref<any[]>(
  localStorage.getItem("historyList")
    ? JSON.parse(localStorage.getItem("historyList") as string)
    : []
);
// 搜索数据详情
const searchDetail = ref<any[]>([]);
// 路由
const router = useRouter();
const notfound = ref(false);
// 防抖定时器
let timer: any = null;
let isInputing = ref(false);

// 1.定义热门搜索，关键字接口数据
const getSearchInitList = async () => {
  const result = await reqGetInitData();
  // console.log("yes", result);
  searchInit.value = result.data;
  // console.log(searchInit);
};
// 2.定义实时请求列表的接口
const getSearchRealList = async (value: string) => {
  const result = await reqGetRealTime(value);
  realTimeList.value = result.data;
};
// 5.搜索数据详情的数据请求
const getSearchDetail = async (value: string) => {
  const result = await reqSearchDetail(value);
  // console.log('detail',result)
  searchDetail.value = result.data.directlyList;
  console.log(searchDetail);
};

// 3.搜索框只要改变就触发，实时点击搜搜列表搜索
// 防抖
const onchange = (value: string) => {
  if (value.trim()) {
    isInputing.value = true;
    isShowSearch.value = true;
    if (isInputing.value) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      isInputing.value = false;
      //展示实时列表页面
      isShowSearch.value = true;
      // 发送请求
      getSearchRealList(value);
      getLocalData(value);
    }, 500);
  }
};
// 4.点击搜索列表数据跳转到详情页面
const btnSearch = async (value: string) => {
  inputValue.value = value;
  await getSearchDetail(value);
  // console.log(searchDetail.value, 888888888888);
  if (searchDetail.value === null) {
    notfound.value = true;
  }
  isSearchBox.value = false;
  isShowSearch.value = false;
  isPageDetail.value = true;
  router.push({
    name: "search",
    query: {
      keyword: value,
      _stat_search: "autoComplete",
    },
  });
  getLocalData(value);
};

// 5.回车确定搜索
const onSearch = async (value: string) => {
  if (value.trim()) {
    await getSearchDetail(value);
    // console.log(searchDetail.value);
    if (searchDetail.value === null) {
      notfound.value = true;
    }
    isShowSearch.value = false;
    isPageDetail.value = true;
    router.push({
      name: "search",
      query: {
        keyword: value,
        _stat_search: "userhand",
      },
    });
    getLocalData(value);
  } else {
    isPageDetail.value = true;
    notfound.value = true;
  }
  console.log(value);
};
// 取消
const onCancel = () => {
  router.go(-1);
};
// 6.本地存储数据
const getLocalData = (value: string) => {
  value = value.trim();
  // 本地存储的长度截取删除
  if (historyList.value.length > 9) {
    // console.log(historyList.value.length)
    historyList.value.splice(-5, 6);
    // console.log(historyList.value.length)
  }
  historyList.value.unshift(value);
  // 去重
  historyList.value = Array.from(new Set(historyList.value));
  // 存入
  window.localStorage.setItem("historyList", JSON.stringify(historyList.value));
};

// 7.删除本地存储
const deleted = () => {
  localStorage.removeItem('historyList')
  historyList.value = []
}

// 挂载，一进页面请求
onMounted(() => {
  getSearchInitList();
});

watch(inputValue, () => {
  if (inputValue.value.length == 0) {
    isSearchBox.value = true;
    isShowSearch.value = false;
    isPageDetail.value = false;
  }


});
</script>

<style scoped lang="less">
.search {
  width: 100%;
  height: 100vh;
  background-color: #eeeeee;

  .record {
    background-color: white;
    border-top: 1px solid #d9d9d9;
    font-size: 14px;
    padding: 0 15px;

    .header {
      height: 45px;
      color: #999;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .icon {
        font-family: 'vant-icon' !important;
        font-size: 20px;
      }
    }
  }

  .detail {
    display: flex;
    flex-wrap: wrap;

    :deep(.van-tag) {
      margin: 0 11.2px 15px 0;
      border-color: #999;
      color: black;
    }

    .active {
      color: red;
      border-color: red;
    }
  }

  .hot {
    background-color: white;
    font-size: 14px;
    padding: 0 15px;
    margin-top: 20px;

    .goods {
      line-height: 45px;
      color: #999;
    }
  }

  .result-goods {
    line-height: 35px;
    background-color: white;
    border-bottom: 1px solid #d9d9d9;
    margin: 0 15px;
    font-size: 15px;
  }

  .detail-goods {
    .top {
      display: flex;
      justify-content: space-around;
      line-height: 40px;
      background-color: #fafafa;
      font-size: 15px;
      border-bottom: 1px solid gray;
    }

    .similar-goods {
      display: flex;
      width: 100%;
      flex-wrap: wrap;
      background-color: #ffffff;
      position: fixed;
      top: 95px;
      bottom: 10px;
      overflow: auto;

      .similar {
        width: 44%;
        color: black;
        background-color: #ffffff;
        font-size: 14px;
        padding: 10px 10px 30px 10px;

        .bigimg {
          width: 170px;
          height: 180px;
          border-radius: 20px;
          margin-bottom: 5px;
        }

        .smallimg {
          height: 18px;
          width: 18px;
          vertical-align: bottom;
        }

        .price {
          .original-price {
            color: rgb(153, 153, 153);
            text-decoration: line-through;
          }
        }

        .content-special {
          background-color: #ffe9eb;
          border-radius: 30px;

          span:first-child {
            background-color: red;
            border-radius: 30px;
            font-size: 11px;
            padding: 3px 5px;
            color: white;
          }

          span:last-child {
            font-size: 11px;
            color: red;
            padding: 3px 3px
          }
        }
      }
    }
  }

  .nofound {
    background-color: #fff;
    height: 100vh;
    display: flex;
    flex-direction: column;
    text-align: center;

    img {
      margin: 50px 0;
    }
  }
}
</style>


